<template>
    <div class="route-config-container">
        <!-- 搜索和操作区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <el-form :model="searchForm" inline>
                    <el-form-item label="菜单名称">
                        <el-input 
                            v-model="searchForm.menuName" 
                            placeholder="请输入菜单名称" 
                            clearable
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item label="路径">
                        <el-input 
                            v-model="searchForm.path" 
                            placeholder="请输入路径" 
                            clearable
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item label="显示状态">
                        <el-select v-model="searchForm.isShow" placeholder="请选择" clearable style="width: 120px">
                            <el-option label="显示" :value="true" />
                            <el-option label="隐藏" :value="false" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-section">
            <el-button type="primary" @click="handleAdd" :icon="Plus">新增菜单</el-button>
            <el-button type="success" @click="handleBatchEnable" :icon="Check" :disabled="!selectedRows.length">批量启用</el-button>
            <el-button type="warning" @click="handleBatchDisable" :icon="Close" :disabled="!selectedRows.length">批量禁用</el-button>
            <el-button type="info" @click="handleExport" :icon="Download">导出</el-button>
            <el-button @click="handleRefresh" :icon="Refresh">刷新</el-button>
            <el-button 
                :type="isTreeView ? 'primary' : 'default'" 
                @click="toggleTreeView" 
            >
                <el-icon>
                    <component :is="isTreeView ? Grid : List" />
                </el-icon>
                {{ isTreeView ? '列表视图' : '树形视图' }}
            </el-button>
            <el-button 
                v-if="isTreeView"
                :type="isExpanded ? 'warning' : 'success'" 
                @click="toggleExpand" 
            >
                <el-icon>
                    <component :is="isExpanded ? ArrowUp : ArrowDown" />
                </el-icon>
                {{ isExpanded ? '折叠菜单' : '展开菜单' }}
            </el-button>
        </div>

        <!-- 表格区域 -->
        <div class="table-section">
            <el-table 
                ref="tableRef"
                v-loading="loading"
                :data="tableData" 
                height="calc(100vh - 280px)"
                :show-overflow-tooltip="true"
                @selection-change="handleSelectionChange"
                row-key="Id"
                :tree-props="isTreeView ? { children: 'Children', hasChildren: 'hasChildren' } : undefined"
                :default-expand-all="isTreeView && isExpanded"
                :indent="isTreeView ? 20 : 0"
                :key="`table-${isTreeView}-${isExpanded}`"
            >
                <el-table-column type="selection" width="55" />
                <!-- <el-table-column prop="Id" label="ID" width="80" /> -->
                <el-table-column prop="Label" label="菜单名称" min-width="150">
                    <template #default="{ row }">
                        <span class="menu-name">{{ row.Label }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="Path" label="路径" min-width="150" />
                <el-table-column prop="Component" label="组件" min-width="200" show-overflow-tooltip />
                <el-table-column prop="ParentId" label="父菜单" width="120">
                    <template #default="{ row }">
                        <el-tag v-if="row.ParentId === 0" type="info" size="small">顶级菜单</el-tag>
                        <span v-else>{{ getParentMenuName(row.ParentId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="Order" label="排序" width="80" />
                <el-table-column prop="IsShow" label="显示状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.IsShow ? 'success' : 'danger'" size="small">
                            {{ row.IsShow ? '显示' : '隐藏' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="IsLayout" label="布局" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.IsLayout ? 'primary' : 'warning'" size="small">
                            {{ row.IsLayout ? '带布局' : '不带布局' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="CreateTime" label="创建时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.CreateTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="UpdateTime" label="更新时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.UpdateTime) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleEdit(scope.row)" size="small">
                            <el-icon><Edit /></el-icon>编辑
                        </el-button>
                        <el-button link type="success" @click="onCopy(scope.row)" size="small">
                            <el-icon><CopyDocument /></el-icon>复制
                        </el-button>
                        <el-popconfirm 
                            title="确定删除此菜单吗？" 
                            @confirm="handleDelete(scope.row)"
                            confirm-button-text="确定"
                            cancel-button-text="取消"
                        >
                            <template #reference>
                                <el-button link type="danger" size="small">
                                    <el-icon><Delete /></el-icon>删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div v-if="!isTreeView" class="pagination-section">
            <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 编辑对话框 -->
        <RouteEditDialog 
            ref="dialogRef" 
            @confirm="onConfirm" 
            :bgcolumnNames="bgcolumnNames" 
            :parentMenuOptions="parentMenuOptions"
        />
        

    </div>
</template>

<script lang="ts" setup>
import { ref, inject, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
    Search, 
    Refresh, 
    Plus, 
    Check, 
    Close, 
    Download, 
    Edit, 
    CopyDocument, 
    Delete,
    Grid,
    List,
    ArrowDown,
    ArrowUp
} from '@element-plus/icons-vue';

import RouteEditDialog from './RouteEditDialog.vue';
import api from '../../api';
import { exportToCSV, menuExportConfig } from '../../utils/exportUtils';
import { showError } from '../../utils/errorHandler';
import { apiPost, apiPostWithResponse, batchOperations } from '../../utils/apiHelper';
import { shallowClone } from '../../utils/performanceHelper';

// 类型定义
interface SearchForm {
    menuName: string;
    path: string;
    isShow: boolean | null;
}

interface Pagination {
    currentPage: number;
    pageSize: number;
    total: number;
}

interface MenuItem {
    Id: number;
    Label: string;
    Path: string;
    Component: string;
    ParentId: number;
    Order: number;
    IsShow: boolean;
    IsLayout: boolean;
    CreateTime: string;
    UpdateTime: string;
    Children?: MenuItem[];
}

// 响应式数据
const loading = ref(false);
const tableData = ref<MenuItem[]>([]);
const selectedRows = ref<MenuItem[]>([]);
const tableRef = ref();
const dialogRef = ref<InstanceType<typeof RouteEditDialog>>();
const parentMenuOptions = ref<Array<{Id: number, Label: string}>>([]);
const isTreeView = ref(true);
const isExpanded = ref(true);

const searchForm = reactive<SearchForm>({
    menuName: '',
    path: '',
    isShow: null
});

const pagination = reactive<Pagination>({
    currentPage: 1,
    pageSize: 20,
    total: 0
});

// 列配置
const bgcolumnNames = [
    // {
    //     "Name": "Id",
    //     "Order": 1,
    //     "Label": "Id",
    //     "Width": 50,
    //     "ControlType": 3,
    //     "TypeName": "Int32",
    //     "IsShow": true,
    //     "IsEditable": false,
    //     "IsNullable": false,
    //     "EnumDic": null
    // },
    {
        "Name": "Path",
        "Order": 100,
        "Label": "路径",
        "Width": 150,
        "ControlType": 3,
        "TypeName": "String",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": true,
        "EnumDic": null
    },
    {
        "Name": "Label",
        "Order": 100,
        "Label": "菜单名",
        "Width": 150,
        "ControlType": 3,
        "TypeName": "String",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": true,
        "EnumDic": null
    },
    {
        "Name": "Component",
        "Order": 100,
        "Label": "组件",
        "Width": 150,
        "ControlType": 3,
        "TypeName": "String",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": true,
        "EnumDic": null
    },
    {
        "Name": "ParentId",
        "Order": 100,
        "Label": "父菜单",
        "ControlType": 3,
        "TypeName": "Int32",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "Order",
        "Order": 100,
        "Label": "Order",
        "ControlType": 3,
        "TypeName": "Int32",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "IsShow",
        "Order": 100,
        "Label": "IsShow",
        "ControlType": 3,
        "TypeName": "Boolean",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "IsLayout",
        "Order": 100,
        "Label": "布局模式",
        "ControlType": 3,
        "TypeName": "Boolean",
        "IsShow": true,
        "IsEditable": true,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "CreateTime",
        "Order": 100,
        "Label": "创建时间",
        "ControlType": 5,
        "TypeName": "DateTime",
        "IsShow": true,
        "IsEditable": false,
        "IsNullable": false,
        "EnumDic": null
    },
    {
        "Name": "UpdateTime",
        "Order": 100,
        "Label": "更新时间",
        "ControlType": 5,
        "TypeName": "Nullable`1",
        "IsShow": true,
        "IsEditable": false,
        "IsNullable": true,
        "EnumDic": null
    }
];

const refreshMenu = inject('refreshMenu') as any;

// 计算属性
const hasSelectedRows = computed(() => selectedRows.value.length > 0);



// 方法
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-';
    return new Date(dateTime).toLocaleString('zh-CN');
};

const getParentMenuName = (parentId: number) => {
    const parent = parentMenuOptions.value.find(item => item.Id === parentId);
    return parent ? parent.Label : '-';
};

const buildQueryParams = () => {
    const params: any = {
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
        SearchConditions: []
    };

    if (searchForm.menuName) {
        params.SearchConditions.push({
            ConditionalModels: [{
                FieldName: 'Label',
                FieldValue: searchForm.menuName,
                ConditionalType: 'Like'
            }]
        });
    }

    if (searchForm.path) {
        params.SearchConditions.push({
            ConditionalModels: [{
                FieldName: 'Path',
                FieldValue: searchForm.path,
                ConditionalType: 'Like'
            }]
        });
    }

    if (searchForm.isShow !== null) {
        params.SearchConditions.push({
            ConditionalModels: [{
                FieldName: 'IsShow',
                FieldValue: searchForm.isShow,
                ConditionalType: 'Equal'
            }]
        });
    }

    return params;
};

const getDataList = async () => {
    loading.value = true;
    
    if (isTreeView.value) {
        // 树形视图：获取树形数据
        const res = await apiPost<any>('RouteConfig/GetTreeData', {});
        if (res) {
            tableData.value = res.Data || [];
            pagination.total = res.Data?.length || 0;
        }
    } else {
        // 列表视图：获取分页数据
        const params = buildQueryParams();
        const res = await apiPost<any>('RouteConfig/List', params);
        
        if (res) {
            tableData.value = res.Data.list || [];
            pagination.total = res.Data.totalNumber || 0;
        }
    }
    
    loading.value = false;
};

const loadParentMenuOptions = async () => {
    // 如果已经有数据，直接返回，避免重复加载
    if (parentMenuOptions.value.length > 0) {
        return;
    }
    
    const res = await apiPost<any>('RouteConfig/GetAllData', {}, '获取父菜单选项失败');
    if (res && res.Data) {
        parentMenuOptions.value = res.Data.map((item: any) => ({ 
            Id: item.Id, 
            Label: item.Label 
        }));
    }
};

const handleSearch = () => {
    pagination.currentPage = 1;
    getDataList();
};

const handleReset = () => {
    Object.assign(searchForm, {
        menuName: '',
        path: '',
        isShow: null
    });
    pagination.currentPage = 1;
    getDataList();
};

const handleAdd = () => {
    const newItem = {
        Id: 0,
        Label: '新菜单',
        Path: '/new-menu',
        Component: '/src/views/NewMenu.vue',
        ParentId: 0,
        Order: 0,
        IsShow: true,
        IsLayout: true,
        CreateTime: new Date().toISOString(),
        UpdateTime: null,
        IsDeleted: false
    };
    dialogRef.value?.open(newItem);
};

const handleEdit = (item: MenuItem) => {
    const editItem = shallowClone(item);
    dialogRef.value?.open(editItem);
};

const onCopy = (item: MenuItem) => {
    const copyItem = shallowClone(item);
    copyItem.Id = 0;
    copyItem.Label = `${copyItem.Label}_副本`;
    copyItem.CreateTime = new Date().toISOString();
    copyItem.UpdateTime = null;
    dialogRef.value?.open(copyItem);
};



const handleDelete = async (item: MenuItem) => {
    const success = await apiPostWithResponse(
        'RouteConfig/Update', 
        { ...item, isDeleted: true }, 
        '删除成功', 
        '删除失败'
    );
    
    if (success) {
        getDataList();
        refreshMenu?.();
    }
};

const handleBatchEnable = async () => {
    try {
        await ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个菜单吗？`, '批量操作', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const operations = selectedRows.value.map(item => 
            () => api.post('RouteConfig/Update', { ...item, IsShow: true })
        );

        const success = await batchOperations(operations, '批量启用成功', '批量启用失败');

        if (success) {
            getDataList();
            refreshMenu?.();
        }
    } catch (error) {
        if (error !== 'cancel') {
            showError(error, '批量启用失败');
        }
    }
};

const handleBatchDisable = async () => {
    try {
        await ElMessageBox.confirm(`确定要禁用选中的 ${selectedRows.value.length} 个菜单吗？`, '批量操作', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const operations = selectedRows.value.map(item => 
            () => api.post('RouteConfig/Update', { ...item, IsShow: false })
        );

        const success = await batchOperations(operations, '批量禁用成功', '批量禁用失败');

        if (success) {
            getDataList();
            refreshMenu?.();
        }
    } catch (error) {
        if (error !== 'cancel') {
            showError(error, '批量禁用失败');
        }
    }
};

const handleExport = () => {
    try {
        const exportData = menuExportConfig.transformData(tableData.value);
        const filename = `菜单配置_${new Date().toISOString().slice(0, 10)}`;
        exportToCSV(exportData, filename, menuExportConfig.headers);
        ElMessage.success('导出成功');
    } catch (error) {
        showError(error, '导出失败');
    }
};

const handleRefresh = () => {
    getDataList();
};

const toggleTreeView = () => {
    isTreeView.value = !isTreeView.value;
    
    // 重置分页
    if (isTreeView.value) {
        pagination.currentPage = 1;
    }
    
    // 显示切换提示
    ElMessage.success(isTreeView.value ? '已切换到树形视图' : '已切换到列表视图');
    
    getDataList();
};

const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
    
    if (isExpanded.value) {
        // 展开所有节点
        const expandRows = (rows: MenuItem[]) => {
            rows.forEach(row => {
                if (row.Children && row.Children.length > 0) {
                    tableRef.value?.toggleRowExpansion(row, true);
                    expandRows(row.Children);
                }
            });
        };
        expandRows(tableData.value);
        ElMessage.success('已展开所有菜单');
    } else {
        // 折叠所有节点
        const collapseRows = (rows: MenuItem[]) => {
            rows.forEach(row => {
                if (row.Children && row.Children.length > 0) {
                    tableRef.value?.toggleRowExpansion(row, false);
                    collapseRows(row.Children);
                }
            });
        };
        collapseRows(tableData.value);
        ElMessage.success('已折叠所有菜单');
    }
};

const handleSelectionChange = (selection: MenuItem[]) => {
    selectedRows.value = selection;
};

const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    pagination.currentPage = 1;
    getDataList();
};

const handleCurrentChange = (page: number) => {
    pagination.currentPage = page;
    getDataList();
};

const onConfirm = async (item: MenuItem) => {
    const success = await apiPostWithResponse(
        'RouteConfig/Update', 
        item, 
        '操作成功', 
        '操作失败'
    );
    
    if (success) {
        refreshMenu?.();
        dialogRef.value?.close();
        getDataList();
    }
};

// 生命周期
onMounted(async () => {
    // 先加载主数据，再异步加载父菜单选项
    await getDataList();
    loadParentMenuOptions(); // 不等待，异步加载
});
</script>

<style scoped>
.route-config-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.search-section {
    margin-bottom: 16px;
}

.search-card {
    background-color: white;
}

.search-card :deep(.el-card__body) {
    padding: 16px;
}

.action-section {
    margin-bottom: 16px;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.table-section {
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    background-color: white;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.menu-name {
    font-weight: 500;
    color: #303133;
}

:deep(.el-table) {
    border-radius: 8px;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
    background-color: #f5f7fa;
}

:deep(.el-button--link) {
    padding: 4px 8px;
}

:deep(.el-tag) {
    border-radius: 4px;
}

:deep(.el-table__expand-icon) {
    margin-right: 8px;
}

:deep(.el-table__expand-icon .el-table__expand-icon-inner) {
    font-size: 12px;
}
</style>